<?php

namespace app\index\common;

use Namshi\JOSE\SimpleJWS;

class JwtAuth
{
    private $key = 'P7LA2o7PkA8xNaAG';
    private $algorithm = 'HS256';

    public function generateToken($payload)
    {
        $jws = new SimpleJWS([
            'alg' => $this->algorithm
        ]);

        $jws->setPayload($payload);

        $jws->sign($this->key);

        return $jws->getTokenString();
    }

    public function verifyToken($token)
    {
        $jws = SimpleJWS::load($token);

        return $jws->isValid($this->key,$this->algorithm);
    }
    public function getPayload($token)
    {
        $jws = SimpleJWS::load($token);

        return $jws->getPayload();
    }

    public function getUserId($token)
    {
        $payload = $this->getPayload($token);

        // 假设 JWT 载荷中包含了用户 ID 字段
        return $payload['userId'] ?? null;
    }
}